import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import {Url, Error} from 'common/js/config'

Vue.use(VueAxios, axios)

// 获取话题列表
export function getTopicsList(val, page = 1) {
  return new Promise((resolve, reject) => {
    axios.get(`${Url}/topics?tab=${val}&page=${page}`)
      .then((response) => {
        resolve(response.data)
      })
      .catch((error) => {
        if (typeof error.response.data === 'object') {
          resolve(error.response.data)
        } else {
          resolve(Error)
        }
      })
  })
}

// 获取话题详情
export function getTopic(id, accesstoken) {
  return new Promise((resolve, reject) => {
    axios.get(`${Url}/topic/${id}?accesstoken=${accesstoken}`)
      .then((response) => {
        resolve(response.data)
      })
      .catch((error) => {
        if (typeof error.response.data === 'object') {
          resolve(error.response.data)
        } else {
          resolve(Error)
        }
      })
  })
}

// 收藏话题
export function collect(id, accesstoken) {
  return new Promise((resolve, reject) => {
    axios.post(`${Url}/topic_collect/collect`, {topic_id: id, accesstoken: accesstoken})
      .then((response) => {
        resolve(response.data)
      })
      .catch((error) => {
        if (typeof error.response.data === 'object') {
          resolve(error.response.data)
        } else {
          resolve(Error)
        }
      })
  })
}

// 取消收藏话题
export function deCollect(id, accesstoken) {
  return new Promise((resolve, reject) => {
    axios.post(`${Url}/topic_collect/de_collect`, {topic_id: id, accesstoken: accesstoken})
      .then((response) => {
        resolve(response.data)
      })
      .catch((error) => {
        if (typeof error.response.data === 'object') {
          resolve(error.response.data)
        } else {
          resolve(Error)
        }
      })
  })
}

// 对回复点赞或取消点赞
export function uped(id, accesstoken) {
  return new Promise((resolve, reject) => {
    axios.post(`${Url}/reply/${id}/ups`, {accesstoken: accesstoken})
      .then((response) => {
        resolve(response.data)
      })
      .catch((error) => {
        if (error.response) {
          resolve(error.response.data)
        } else {
          reject(Error)
        }
      })
  })
}
